import axios from "axios";
import store from "@/store";
import Storage from "@/utils/storageUtils"
import {Message} from "element-ui"
import router from "@/router";

Date.prototype.format = function (fmt) {
  let o = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S": this.getMilliseconds()
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
  return fmt
}

axios.interceptors.request.use(config => {
  //设置token
  config.headers.Authorization = store.getters.getToken ? store.getters.getToken : Storage.Local.get("token");
  return config;
});

axios.interceptors.response.use(res => {
  console.log(res);
  if (res.data.code == 401 || res.data.code == 413) {
    console.log(123);
    Message({
      message: res.data.message,
      type: "error"
    });
    router.push({
      path: "/login",
      name: "Login"
    });
    return;
  }
  if (res.data.code != 200) {
    Message({
      message: res.data.message,
      type: "error"
    });
  }
  return res;
});

export default {
  get(url, params) {
    return axios({
      method: "GET",
      url,
      params,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      }
    })
  },
  post(url, data) {
    return axios({
      method: "POST",
      url,
      data,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      }
    })
  },
  put(url, data) {
    return axios({
      method: "PUT",
      url,
      data,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      }
    })
  },
  delete(url, params) {
    return axios({
      method: "DELETE",
      url,
      params,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      }
    })
  }
}
